﻿using System.ComponentModel.DataAnnotations;
using Bookify.Application.Exceptions;
using Microsoft.AspNetCore.Mvc;
using ValidationException = Bookify.Application.Exceptions.ValidationException;

namespace Bookify.Api.Middleware
{
    public class ExceptionHandlingMiddleware(RequestDelegate next,ILogger<ExceptionHandlingMiddleware> logger)
    {
        public async Task InvokeAsync(HttpContext context)
        {
			try
			{
				await next(context);
			}
			catch (Exception exception)
			{

				logger.LogError(exception,"发生异常:{Message}",exception.Message);

				var exceptionDetails = GetExceptionDetails(exception);
				var problemDetails = new ProblemDetails
				{
					Status = exceptionDetails.Status,
					Type = exceptionDetails.Type,
					Title = exceptionDetails.Title,
					Detail = exceptionDetails.Detail,
				};

				if(exceptionDetails.Errors is not null)
				{
					problemDetails.Extensions["errors"] = exceptionDetails.Errors;
				}

				context.Response.StatusCode = exceptionDetails.Status;
				await context.Response.WriteAsJsonAsync(problemDetails);
			}
        }

		private static ExceptionDetails GetExceptionDetails(Exception exception)
		{
			return exception switch
			{
				ValidationException validationException => new ExceptionDetails(
					StatusCodes.Status400BadRequest,
                    "ValidationFailure",
                    "Validation error",
                    "发生了一个或多个验证错误",
                    validationException.Errors),
					_ => new ExceptionDetails(
						StatusCodes.Status500InternalServerError,
						"ServerError",
						"Server error",
						"内部发生意外错误",
						null)

			};
		}

		internal record ExceptionDetails
		(
            int Status,
			string Type,
			string Title,
			string Detail,
			IEnumerable<object>? Errors);
		
    }
}
